import { pageListCustomerProducts, pageListProductCustomers } from '@/services/product/product_api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
    FooterToolbar,
    ModalForm,
    PageContainer,
    ProDescriptions,
    ProFormText,
    ProFormTextArea,
    ProTable,
    TableDropdown
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, Input, message, Modal, Tabs, Tag } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import AddForm from './components/AddForm';
import { PriceRuleVO } from "../constants"
import { set } from 'lodash';
import AddFormProduct from './components/AddFormProduct';


const { TabPane } = Tabs;



const TableList: React.FC = () => {
    /**
  * @en-US International configuration
  * @zh-CN 国际化配置
  * */
    const intl = useIntl();
    /**
     * @en-US Pop-up window of new window
     * @zh-CN 新建窗口的弹窗
     *  */
    const [createModalOpen, handleModalOpen] = useState<boolean>(false);
    /**
     * @en-US The pop-up window of the distribution update window
     * @zh-CN 分布更新窗口的弹窗
     * */
    const [loadingCustomer, setLoadingCustomer] = useState(false);
    const [loadingProduct, setLoadingProduct] = useState(false);
    const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
    const [updateProductModalOpen, handleUpdateProductModalOpen] = useState<boolean>(false);


    const actionRefCustomer = useRef<ActionType>();
    const actionRefProduct = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<any>();
    const [currentProductCustomer, setCurrentProductCustomer] = useState<any>();



    const [activeKey, setActiveKey] = useState('customer');
    const handleTabChange = (key: string) => {
        setActiveKey(key);
        // 根据当前tab触发对应表格刷新
        if (key === 'customer' && actionRefCustomer.current) {
            actionRefCustomer.current.reload();
        } else if (key === 'product' && actionRefProduct.current) {
            actionRefProduct.current.reload();
        }
    };


    const pageQueryCustomer = async (params, sorter, filter) => {
        // 表单搜索项会从 params 传入，传递给后端接口。
        // console.log(params, sorter, filter);
        // const { current, pageSize, customerCode, customerName, customerStatus } = params
        try {
            const response = await pageListCustomerProducts(params);
            if (response.code != 0) {
                if (!response.msg) {
                    throw new Error(intl.formatMessage({ id: "request.error.create" }));
                } else {
                    message.error(response.msg);
                }
            }
            return response.data;
        } catch (error) {
            console.error(error);
            message.error(intl.formatMessage({ id: "request.error.retry" }));
        }
    }

    const pageQueryProduct = async (params, sorter, filter) => {
        // 表单搜索项会从 params 传入，传递给后端接口。
        // console.log(params, sorter, filter);
        // const { current, pageSize, customerCode, customerName, customerStatus } = params

        try {
            const response = await pageListProductCustomers(params);
            if (response.code != 0) {
                if (!response.msg) {
                    throw new Error(intl.formatMessage({ id: "request.error.create" }));
                } else {
                    message.error(response.msg);
                }
            }
            return response.data;
        } catch (error) {
            console.error(error);
            message.error(intl.formatMessage({ id: "request.error.retry" }));
        }
    }


    const productColumns: ProColumns<ProductCustomerVo>[] = [
        {
            title: (
                <FormattedMessage
                    id="pages.product.prName"
                    defaultMessage="Name"
                />
            ),
            dataIndex: "prName",
            key: "prName",
            width: 200,
            sorter: true, // 允许排序
            search: {
                transform: (value) => value, // 可选：搜索转换逻辑
            },
        },
        {
            title: (
                <FormattedMessage
                    id="pages.product.prCode"
                    defaultMessage="Code"
                />
            ),
            dataIndex: "prCode",
            key: "prCode",
            width: 200,
            sorter: true,
            search: {
                transform: (value) => value,
            },
        },
        {
            title: (
                <FormattedMessage id="pages.searchTable.titleStatus" defaultMessage="Status" />
            ),
            dataIndex: "prStatus",
            key: "prStatus",
            width: 150,
            valueType: "select", // 下拉选择类型
            valueEnum: {
                1: {
                    text: (
                        <FormattedMessage
                            id="pages.status.disabled"
                            defaultMessage="Disabled"
                        />
                    ),
                    status: "error",
                },
                0: {
                    text: (
                        <FormattedMessage
                            id="pages.status.enabled"
                            defaultMessage="Enabled"
                        />
                    ),
                    status: "success",
                },
            },
            sorter: true,
            search: {
                transform: (value) => value,
            },
        },
        {
            title: (
                <FormattedMessage
                    id="pages.searchTable.customer.list"
                    defaultMessage="Customer List"
                />
            ),
            key: "customers",
            dataIndex: 'customers',
            render: (_, record) => (
                <div>
                    {record.customers?.map(tag => (
                        <Tag key={tag.customerCode} color="blue">{tag.customerName}</Tag>
                    ))}
                </div>
            ),
            search: false,
        },
        {
            title: (
                <FormattedMessage id="pages.operating" defaultMessage="Operating" />
            ),
            dataIndex: "option",
            valueType: "option",
            fixed: "right",
            width: 160,
            render: (_, record) => [
                <a
                    key="editProduct"
                    onClick={async () => {
                        console.log("prod:"+JSON.stringify(record));
                        setCurrentProductCustomer(record);
                        handleUpdateProductModalOpen(true); // 打开编辑弹窗
                    }}
                >
                    <FormattedMessage id="pages.edit" defaultMessage="Edit" />
                </a>,
            ],
        },
    ];


    const customerColumns: ProColumns<CustomerProductVo>[] = [
        {
            title: (
                <FormattedMessage
                    id="pages.addForm.customer.customerName"
                    defaultMessage="Customer Name"
                />
            ),
            dataIndex: "customerName",
            key: "customerName",
            width: 200,
            sorter: true, // 允许排序
            search: {
                transform: (value) => value, // 可选：搜索转换逻辑
            },
        },
        {
            title: (
                <FormattedMessage
                    id="pages.addForm.customer.customerCode"
                    defaultMessage="Customer Code"
                />
            ),
            dataIndex: "customerCode",
            key: "customerCode",
            sorter: true,
            width: 200,
            search: {
                transform: (value) => value,
            },
        },
        {
            title: (
                <FormattedMessage id="pages.searchTable.titleStatus" defaultMessage="Status" />
            ),
            dataIndex: "customerStatus",
            key: "customerStatus",
            width: 150,
            valueType: "select", // 下拉选择类型
            valueEnum: {
                1: {
                    text: (
                        <FormattedMessage
                            id="pages.status.disabled"
                            defaultMessage="Disabled"
                        />
                    ),
                    status: "error",
                },
                0: {
                    text: (
                        <FormattedMessage
                            id="pages.status.enabled"
                            defaultMessage="Enabled"
                        />
                    ),
                    status: "success",
                },
            },
            sorter: true,
            search: {
                transform: (value) => value,
            },
        },
        {
            title: (
                <FormattedMessage
                    id="pages.product.name"
                    defaultMessage="Product Name"
                />
            ),
            key: "products",
            dataIndex: 'products',
            render: (_, record) => (
                <div>
                    {record.products?.map(tag => (
                        <Tag key={tag.prCode} color="blue">{tag.prName}</Tag>
                    ))}
                </div>
            ),
            search: false,
        },
        {
            title: (
                <FormattedMessage id="pages.operating" defaultMessage="Operating" />
            ),
            dataIndex: "option",
            valueType: "option",
            fixed: "right",
            width: 160,
            render: (_, record) => [
                <a
                    key="edit"
                    onClick={async () => {
                        setCurrentRow(record);
                        handleUpdateModalOpen(true); // 打开编辑弹窗
                    }}
                >
                    <FormattedMessage id="pages.edit" defaultMessage="Edit" />
                </a>,
            ],
        },
    ];


    const refreshTable =(key:string)=>{
        if (key === 'customer' && actionRefCustomer.current) {
            actionRefCustomer.current.reload();
        } else if (key === 'product' && actionRefProduct.current) {
            actionRefProduct.current.reload();
        }
    }

    return (
      <PageContainer title={false}>
        <Tabs activeKey={activeKey} onChange={handleTabChange}>
          <TabPane
            tab={intl.formatMessage({
              id: "pages.product.customer.list",
              defaultMessage: "Customer Product List",
            })}
            key="customer"
          >
            <ProTable<CustomerProductVo, API.PageParams>
              actionRef={actionRefCustomer}
              loading={loadingCustomer}
              rowKey="key"
              search={{
                labelWidth: 120,
              }}
              request={pageQueryCustomer}
              columns={customerColumns}
            />
          </TabPane>
          <TabPane
            tab={intl.formatMessage({
              id: "pages.product.product.list",
              defaultMessage: "Product Customer List",
            })}
            key="product"
          >
            <ProTable<ProductCustomerVo, API.PageParams>
              actionRef={actionRefProduct}
              loading={loadingProduct}
              rowKey="key"
              search={{
                labelWidth: 120,
              }}
              request={pageQueryProduct}
              columns={productColumns}
            />
          </TabPane>
        </Tabs>

        <AddFormProduct
          visible={updateProductModalOpen}
          values={currentProductCustomer}
          // onOpenChange={handleModalOpen}
          onCancel={async () => {
            handleUpdateProductModalOpen(false);
          }}
          onSuccess={function (): void {
            handleUpdateProductModalOpen(false);
            setCurrentProductCustomer(undefined);
            refreshTable(activeKey);
          }}
        />

        <AddForm
          visible={updateModalOpen}
          values={currentRow}
          onCancel={async () => {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
          }}
          onSuccess={function (): void {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            refreshTable(activeKey);
          }}
        />
      </PageContainer>
    );
};

export default TableList;
